// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package gtfs_rt

import (
	pb "apiote.xyz/p/szczanieckiej/gtfs_rt/transit_realtime"

	"fmt"
	"io"
	"net/http"
	"time"

	"google.golang.org/protobuf/proto"
)

func GetMessages(feedID string, feedURL string) (*pb.FeedMessage, error) {
	var message *pb.FeedMessage
	client := http.Client{Timeout: 5 * time.Second}
	response, err := client.Get(feedURL)
	if err != nil {
		return nil, fmt.Errorf("cannot download from ‘%s’: %w", feedURL, err)
	}
	message = new(pb.FeedMessage)
	bytes, err := io.ReadAll(response.Body)
	if err != nil {
		return nil, fmt.Errorf("cannot read response for ‘%s’: %w", feedURL, err)
	}
	if err := proto.Unmarshal(bytes, message); err != nil {
		return nil, fmt.Errorf("Failed to parse message: %w", err)
	}
	return message, nil
}
